<template>
  <el-select v-bind="$attrs" :v-loading="loading" :empty-values="[null]" :value-on-clear="null"
    @visible-change="visibleChange" filterable clearable>
    <!-- 特定的页脚插槽 -->
    <el-option v-for="item in calculateOptions" :key="item" :label="item.label
    ? item.label
    : item[props.descKey]
      ? item.name + `(${item[props.descKey]})`
      : item.name
    " :value="item[props.valueKey]
    ? item[props.valueKey]
    : item.id
      ? item.id
      : item.value
    " />
    <!-- 动态渲染 footer 插槽 -->
    <template v-if="$slots.footer" #footer>
      <slot name="footer"></slot>
    </template>
  </el-select>
</template>
<script setup name="YSelect">
const loading = ref(false);
const dynamicOptions = ref();

const props = defineProps({
  options: { type: Array, default: [] },
  descKey: { type: String, default: "username" },
  valueKey: { type: String, default: "id" },
  optionsFunc: { type: Function, default: undefined },
  optionsParams: { type: Object, default: { nopaginate: true } },
});

const calculateOptions = computed(() => {
  return dynamicOptions.value ? dynamicOptions.value : props.options;
});

/** 获取选项列表 */
function visibleChange(val) {
  if (props.optionsFunc) {
    if (val) {
      loading.value = true;
      props.optionsFunc(props.optionsParams).then((response) => {
        dynamicOptions.value = response.data;
        loading.value = false;
      });
    }
  }
}
</script>
